package com.example.project.controller;

import com.example.project.entity.Goods;
//import com.example.project.entity.User;
import com.example.project.service.GoodsService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author Lenovo
 * @version 1.0
 * @date 2025/4/8 11:34
 * @className IndexController
 */
@Controller
public class IndexController {

    @Autowired
    private GoodsService goodsService;
    private static int  PAGE_SIZE =5;//分页查询，一页多少条

    @GetMapping("/")
    public String index(@RequestParam(defaultValue = "1") int page, Model model, HttpSession session) {
        //必须要登录之后才能访问
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser == null){
            return "redirect:/user/login";
        }


        // 获取总记录数
        long total = goodsService.count();
        // 计算总页数
        int totalPages = (int) Math.ceil((double) total / PAGE_SIZE);
        // 确保页码在有效范围内
        if (page < 1) page = 1;
        if (page > totalPages) page = totalPages;

        // 获取当前页的数据
        List<Goods> goodList = goodsService.findByPage(page, PAGE_SIZE);

        model.addAttribute("goodList", goodList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("total", total);
        return "index";
    }
}
